package service

import (
	"fmt"
	"log"
	"net/http"
	"strings"

	"os"

	"tool/global"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type File struct {
	ServiceBase
}

var logger *zap.Logger
var fileD string = "./template/public"

func (s File) Fstart(c *gin.Context) {
	s.Show("filerename", nil, c)
}

func (s File) FilereNameReplace(c *gin.Context) {

	fileroute := c.DefaultPostForm("fileroute", "")
	fileserch := c.DefaultPostForm("fileserch", "")
	filreplace := c.DefaultPostForm("filreplace", "")

	fs, err := os.Stat(fileroute)
	if err != nil {
		fmt.Println(err.Error())
	}
	if fs.IsDir() == false {
		logger.Error(
			"错误:",
			zap.String("判断目录", "---------不是目录---------"),
		)
	}
	fDir(fileroute, fileserch, filreplace, 0)
}

func fDir(path string, oldStr string, xnewStr string, num int) {

	fInfo, fErr := os.ReadDir(path)
	if fErr != nil {
		fmt.Println(fErr.Error())
	}

	var err error
	for _, v := range fInfo {

		if v.IsDir() == true {

			fDir(path+"/"+v.Name(), oldStr, xnewStr, num+1)
		} else {

			newStr := strings.Replace(v.Name(), oldStr, xnewStr, -1)
			if err = os.Rename(path+"/"+v.Name(), path+"/"+newStr); err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println("操作成功--" + v.Name() + "修改为-->" + newStr)
			}
		}
	}
}

func (s File) Downup(c *gin.Context) {
	s.Show("downup", nil, c)
}

func (s File) Fileup(c *gin.Context) {

	// 设置最大的上传文件大小
	global.Route.MaxMultipartMemory = 100 << 20 // 100 GiB
	fileUpload, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	} else {
		// 保存文件到服务器
		if err := c.SaveUploadedFile(fileUpload, fmt.Sprintf(fileD+"/%s", fileUpload.Filename)); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"message": "文件上传成功",
			})
		}
	}
}

func (s File) Downlist(c *gin.Context) {
	files, err := os.ReadDir(fileD)
	if err != nil {
		log.Fatal(err)
	}
	fileLen := len(files)
	dirFile := make([]string, 0, fileLen)
	for i := 0; i < fileLen; i++ {
		dirFile = append(dirFile, files[i].Name())
	}
	c.JSON(http.StatusOK, gin.H{
		"file_list": dirFile,
	})
}
